package com.zgh.util;

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class PropertiesUtils {
	/**
	 * 根据文件资源，加载属性文件
	 * @param res
	 * @return
	 */
	public static Properties loadResource(Resource res) throws Exception{
		try {
			return PropertiesLoaderUtils.loadProperties(res);
		} catch (IOException e) {
			throw new Exception(e);
		}
	}
	/**
	 * 根据文件资源路径，加载属性文件
	 * @param path
	 * @return
	 */
	public static Properties loadResource(String path) throws Exception{
		return loadResource(ResourceUtils.getResource(path));
	}
	
	
	/**
	 * 将属性转换为map
	 * @param p
	 * @return
	 */
	public static Map getPropertiesMap(Properties p){
		Map map = new HashMap();
		Enumeration names = p.propertyNames(); 
		while(names.hasMoreElements()) {
			String name = (String) names.nextElement();
			String value = p.getProperty(name);
			map.put(name, value);
		}
		return map;
	}
	/**
	 * 根据文件资源，将属性转换为map
	 * @param res
	 * @return
	 */
	public static Map getPropertiesMap(Resource res) throws Exception{
		return getPropertiesMap(loadResource(res));
	}

}
